package com.kaifamiao.servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.Iterator;

@WebServlet( name = "init-param-servlet",
             urlPatterns = {"/init","/init/param"},
             initParams = {
                            @WebInitParam( name = "encoding", value = "GBK" ),
                            @WebInitParam( name = "version", value = "第二个NewB版" )
             })
public class InitParamServlet extends HttpServlet {


    public static final String NAME = "encoding";
    public static final String DEFAULT = "UTF-8";

    private String encoding;

    @Override
    public void init() throws ServletException {
        // 通过调用再Servlet接口中定义的方法获得ServletConfig对象
        ServletConfig config = this.getServletConfig();
        // 根据参数名称获得初始化参数的值
        encoding = config.getInitParameter( NAME ); // this.getInitParameter( NAME )
        // 当初始化参数值为 空 或 空白 则使用默认值，否则使用用户设置的值
        encoding = encoding == null || encoding.isBlank() ? DEFAULT : encoding;
        // 若JVM支持用于设置的编码则使用用于设置的编码，否则使用默认值
        encoding = Charset.isSupported( encoding ) ? encoding : DEFAULT;
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding( encoding );
        response.setCharacterEncoding( encoding );
        response.setContentType( "text/html; charset=" + encoding );
        PrintWriter out = response.getWriter();
        // 要注意 GenericServlet 实现了 ServletConfig 接口中所有方法
        // 而我们继承的 HttpServlet 又继承了 GenericServlet
        // 因此可以直接调用在 ServletConfig 接口中声明的方法
        Enumeration<String> names = this.getInitParameterNames();
        Iterator<String> itor = names.asIterator();
        while( itor.hasNext() ) {
            String name = itor.next();
            String value = this.getInitParameter( name );
            out.println("<p align='center'>" + name + " : " + value + "</p>");
        }
    }

}
